package com.neu.cpsp.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5技术加密解密
 */
public class MD5Util {
    public String string2MD5(String str) {
        MessageDigest md5 = null;
        try{
            md5 = MessageDigest.getInstance("MD5");
        }catch (NoSuchAlgorithmException e) {
            System.out.println(e.toString());
            e.printStackTrace();
        }
        char[] chars = str.toCharArray();
        byte[] bytes = new byte[chars.length];

        for (int i = 0; i < chars.length; i++) {
            bytes[i] = (byte) chars[i];
        }
        assert md5 != null;
        byte[] md5Bytes = md5.digest(bytes);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0;i < md5Bytes.length;i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append(0);
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    /**
     * 加密解密函数，执行一次加密，执行两次解密
     * @param str
     * @return
     */
    public String convertMD5(String str) {
        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            chars[i] = (char) (chars[i] ^ 't');
        }
        return new String(chars);
    }
}
